const {
  findUserById,
  findUserByName,
  findUserAll,
  createUser,
} = require("../service/user.service");
const { rolePermission } = require("../utils/configuration.js");

const { createToken } = require("../utils/setToken");
const { convertToChinaTime, getCurrentTime } = require("../utils/time");

//登录
exports.doLogin = async (ctx, next) => {
  let { username, password } = ctx.request.body;
  ctx.logger.info(username, password);
  if (!username || !password) {
    ctx.fail("用户名和密码不能为空");
    return;
  }
  const res = await findUserByName(username);
  if (res.length === 0) {
    return ctx.fail("用户不存在");
  }
  //生成token
  const token = createToken(res[0]);
  ctx.success("登录成功", { token });
  await next();
};
//获取用户信息
exports.getUserInfo = async (ctx, next) => {
  const user = ctx.state.user;
  if (!user) {
    return ctx.fail("用户信息获取失败");
  }
  const { id } = user;
  const res = await findUserById(id);
  if (res && res.length == 0) {
    return ctx.fail("用户信息不存在");
  }
  ctx.success("获取用户信息成功", res[0]);
  await next();
};

//退出登录
exports.logout = async (ctx, next) => {
  global.blackTokenList.push(ctx.headers.authorization);
  ctx.tokenExpires("退出成功");
  await next();
};

//查询用户列表
exports.findUserList = async (ctx, next) => {
  const res = await findUserAll();
  const data = res.map((item) => ({
    ...item,
    reg_time: convertToChinaTime(item.reg_time),
  }));
  ctx.success("获取用户列表成功", data);
  await next();
};

//创建用户
exports.createUserList = async (ctx, next) => {
  ctx.verifyParams({
    username: { type: "string", required: true },
    password: { type: "string", required: true },
    avatar_url: { type: "number", required: true },
  });
  const { id } = ctx.state.user;
  const { username, password, roleId } = ctx.request.body;
  const user = await findUserById(id);
  const role_id = user[0].role_id;
  if (role_id !== rolePermission) {
    return ctx.fail("权限不足,无法创建用户");
  }
  const reg_time = getCurrentTime();
  const res = await createUser(username, password, roleId, reg_time);
  ctx.success("创建用户成功", res);
  await next();
};
